// let utils = require('../../../../utils/util');
const {
    http
} = require('../../../../utils/apiutils.js');
import {
    input
} from '../../../../utils/tools'
import {
    formatTime1
} from '../../../../utils/util'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        searchQuery: {
            content: '',
            type: ''
        },
        img: [],
        fileListImg: [],
        allWork: [{
            key: '汽车',
            value: 1
        }, {
            key: '电动车',
            value: 2
        }, {
            key: '其他',
            value: 3
        }, ],
        checked: true,
        form: {
            id: '',
            lostDesc: '',
            lostType: '',
            contactMe: 1,
            openid: '',
            phone: '',
            lostPic: '',
            lat: 0,
            lng: 0,
            username: ''
        },
        loading: false,
        mshow: false,
        type: '',
        firstfive: [],
        dataList: [],
        isCanDraw: false,
        obj: {},
        bgImg: 'http://linghuoimage.xbbzp.com/FtSQneu0FbMtK5QvJhAWG5_SqvlK',
        code_img: 'http://linghuoimage.xbbzp.com/Fs2WnGKVDZPvdCAnFqhe2y3UrGK7',
        lookdata: {},
        back: false,
        num1: 0, // 发布数
        num2: 0, // 帮助数
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            ['form.openid']: getApp().globalData.userInfo.openid,
            ['form.unionid']: getApp().globalData.userInfo.unionid,
            ['form.phone']: getApp().globalData.userInfo.phone,
            ['form.username']: getApp().globalData.userInfo.realName || getApp().globalData.userInfo.username,
        })
        this.getList()
        this.getNumber()
    },
    deletaImg: function (e) {
        //  console.log("-----",e);
        let index = e.detail.index;
        this.data.fileListImg.splice(index, 1);
        this.setData({
            fileListImg: this.data.fileListImg,
        })
    },
    tabClick(event) {
        this.setData({
            ['form.lostType']: event.currentTarget.dataset.index * 1 + 1
        })
    },
    input(event) {
        input.bind(this)(event)
    },
    verify() {
        let params = JSON.parse(JSON.stringify(this.data.form));
        if (this.data.loading) return;
        this.data.loading = true;
        if (!params.lostType) {
            wx.showToast({
                title: '失物类型不能为空',
                icon: "none"
            })
            return false;
        }
        if (!params.lostDesc) {
            wx.showToast({
                title: '失物描述不能为空',
                icon: "none"
            })
            return false;
        }
        if (!params.place) {
            wx.showToast({
                title: '地址信息不能为空',
                icon: "none"
            })
            return false;
        }
        if (!(this.data.fileListImg.length > 0)) {
            wx.showToast({
                title: '请上传图片',
                icon: "none"
            })
            this.data.loading = false;
            return false;
        }
        if (this.data.fileListImg.length > 0) {
            this.upDataFile(this.data.fileListImg, 0, 1);
            return false;
        }
    },
    dingyue() {
        this.verify();
    },
    submit() {
        wx.showLoading({
            mask: true
        })
        let params = JSON.parse(JSON.stringify(this.data.form));
        params.lostPic = this.data.img.join(',')
        var that = this;
        if (this.data.form.id) {
            http.updatePost(this.data.factoryJob,
                function (res) {
                    wx.hideLoading()
                    if (res.success) {
                        wx.showModal({
                            title: "提示",
                            content: "修改岗位信息成功",
                            showCancel: false,
                            success: function () {
                                wx.navigateBack({
                                    delta: 1,
                                });

                            },
                        })
                    } else {
                        wx.showToast({
                            title: res.message,
                            icon: "none",
                        })
                    }
                },
                function (err) {
                    wx.hideLoading()
                })
        } else {
            console.log("--保存信息--")
            wx.showLoading({
                title: '加载中...',
                mask: true
            })
            http.lostSave(params,
                function (res) {
                    wx.hideLoading()
                    if (res.code == 0) {
                        wx.showModal({
                            title: "提示",
                            content: "发布成功",
                            showCancel: false,
                            success: function () {
                                that.setData({
                                    ['form.lostDesc']: '',
                                    ['form.lostPic']: '',
                                    ['form.place']: '',
                                    fileListImg: [],
                                    img: []
                                })
                                that.getList()
                            },
                        })
                    } else {
                        wx.showToast({
                            title: res.message,
                            icon: "none",
                        })
                    }
                },
                function (err) {
                    wx.hideLoading()
                })

        }
        wx.hideLoading({})
    },
    afterRead(event) {
        const {
            file
        } = event.detail;
        if (file.type == "image") {
            this.setData({
                fileListImg: [...this.data.fileListImg, file],
            })
        } else {
            wx.showToast({
                title: '请上传图片文件',
            })
        }
    },
    upDataFile(data, index, type) {
        let item = data[index];
        console.log("-----", item);
        var that = this;
        var p = {
            url: item.url,
            name: "file",
            formData: {},
        }
        wx.showLoading({
            mask: true
        })
        http.upDataFile(p,
            function (res) {
                console.log("---上传图片-", res);
                wx.hideLoading({
                    success: (res) => {},
                })
                if (res.code == 0) {
                    if (type == 1) {
                        that.data.img.push(res.data);
                        if (index == data.length - 1) {
                            that.submit()
                            that.data.loading = false;
                        } else {
                            console.log("--继续执行--", index, data.length - 1);
                            that.upDataFile(data, index + 1, type)
                        }
                    } else {
                        wx.showToast({
                            title: res.message,
                            icon: "nene",
                        })
                        that.data.loading = false;
                    }
                }
            },
            function (err) {
                wx.hideLoading()
                that.data.loading = false;
            })
    },
    onclickSure() {
        if (this.data.fileListImg.length > 0) {
            this.upDataFile(this.data.fileListImg, 0, 1);
            return false;
        }
    },
    onChange(e) {
        this.setData({
            ['form.contactMe']: e.detail ? 1 : 2
        })
        if (e.detail && this.data.lat == 0) {
            this.isGetSetting();
        }
    },
    isGetSetting() {
        // 判断用户是否授权
        var that = this;
        wx.getLocation({
            type: 'gcj02',
            success: function (res) {
                that.data.lat = res.latitude;
                that.data.lng = res.longitude;
                console.log("-----用户位置信息--", res)
            },
            fail: function (res) {
                wx.showModal({
                    title: '获取当前定位',
                    content: '请打开设置，允许小程序使用位置信息',
                    cancelText: '不允许',
                    confirmText: '打开设置',
                    success(res1) {
                        if (res1.confirm) {
                            wx.openSetting({
                                withSubscriptions: true,
                                success(res) {
                                    if (res.authSetting['scope.userLocation']) {
                                        wx.nextTick(() => {
                                            that.isGetSetting();
                                        })
                                    }
                                }
                            })
                        }
                    },
                    fail(err) {
                        console.log(err)
                    }
                })
            },
        })
    },
    aa() {
        console.log(777)
    },
    getList() {
        let params = Object.assign({}, this.data.searchQuery)
        http.lostList(params, res => {
            if (res.code == 0) {
                res.data.records.filter(item => {
                    item.createTime = formatTime1(item.createTime)
                    let name = item.username;
                    item.username = (name != null) && name[0] + '**'
                    return item;
                })
                let arr = []
                if (res.data.records.length > 5) {
                    arr = res.data.records.slice(0, 5)
                    // arr=res.data.records
                } else {
                    arr = [...res.data.records]
                }
                wx.nextTick(() => {
                    this.setData({
                        dataList: res.data.records,
                        firstfive: arr
                    })
                    console.log(this.data.firstfive)
                })
            }
        }, err => {})
    },
    closem1() {
        this.setData({
            mshow: !this.data.mshow
        })
    },
    typechange(e) {
        let key = e.currentTarget.dataset.key
        this.setData({
            [key]: this.data.allWork[e.detail.value].value
        })
    },
    createShareImage() {
        // this.setData({
        // 	isCanDraw: !this.data.isCanDraw
        // })
        wx.previewImage({
            showmenu: true,
            urls: ['http://linghuoimage.xbbzp.com/FjJweNFCZZGYTozRDJ8AUobRD7uP'],
            // urls: ['http://linghuoimage.xbbzp.com/FvQMAd_THsWDuTX4PGfttddRLp7U'],
            // urls: ['http://linghuoimage.xbbzp.com/Fo7Wv7FFziwAvH8fFDeFSw_CetA3'],
        })
    },
    maskTel(e) {
        if (this.data.lookdata.contactMe == 2) return
        wx.makePhoneCall({
            phoneNumber: e.currentTarget.dataset.tel,
            success() {
                let params = {
                    openid: getApp().globalData.userInfo.openid,
                    unionid: getApp().globalData.userInfo.unionid,
                    beOpenid: e.currentTarget.dataset.openid,
                    phone: e.currentTarget.dataset.tel
                }
                http.saveContactRecord(params, res => {}, err => {})
            }
        })
    },
    showm(e) {
        // 显示详细信息
        this.setData({
            lookdata: this.data.dataList[e.currentTarget.dataset.index],
            mshow: true
        })
    },
    backTop() {
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 300,
        })
    },
    onPageScroll(e) {
        if (e.scrollTop > 800 && !this.data.back) {
            this.setData({
                back: true
            })
        }
        if (e.scrollTop < 800 && this.data.back) {
            this.setData({
                back: false
            })
        }
    },
    getNumber() {
        http.losttotal({}, res => {
            this.setData({
                num1: res.data.fbs,
                num2: res.data.bzs
            })
        }, err => {})
    },
    getLocation() {
        let _this = this;
        wx.chooseLocation({
            success(res) {
                console.log(res)
                _this.setData({
                    ['form.lat']: res.latitude,
                    ['form.lng']: res.longitude,
                    ['form.place']: res.address + ' ' + res.name
                })
            }
        })
    },
    toaddr(e) {
        let item = e.currentTarget.dataset.item
        if (!item.place) {
            return
        }
        wx.openLocation({ //​使用微信内置地图查看位置。
            latitude: Number(item.lat), //要去的纬度-地址
            longitude: Number(item.lng), //要去的经度-地址
            name: item.place.split(' ')[0],
            address: item.place.split(' ')[1]
        })
    },
    onShareAppMessage: function () {
        var that = this;
        // 设置菜单中的转发按钮触发转发事件时的转发内容
        var code = getApp().globalData.userInfo.inviteCode
        debugger
        var shareObj = {
            title: that.data.lookdata.lostDesc, // 默认是小程序的名称(可以写slogan等)
            path: '/pages/index/index?route=searchcar&code=' + code, // 默认是当前页面，必须是以‘/'开头的完整路径
            imageUrl: that.data.lookdata.lostPic,
            success: function (res) {
                // 转发成功之后的回调
                if (res.errMsg == 'shareAppMessage:ok') {

                }
            }
        }
        // 返回shareObj
        return shareObj;

    },
})